﻿using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Prism.StoreApps;
using System;
using System.Diagnostics;
using Windows.Media.Capture;
using WinRT.SIP.UI.Common;
using WinRT.SIP.UILogic.Events;

namespace WinRT.SIP.UI.Views
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class CallPage : VisualStateAwarePage
    {
        private MediaCapture _captureManager;

        public CallPage()
        {
            this.InitializeComponent();
            InitializeMediaCapture();

            var eventAggregator = ServiceLocator.Resolve<IEventAggregator>();
            eventAggregator.GetEvent<VideoStateChangedEvent>().Subscribe((videoOn) =>
                {
                    if (videoOn)
                    {
                        StartWebCam();
                    }
                    else
                    {
                        StopWebCam();
                    }
                });
        }

        private async void InitializeMediaCapture()
        {
            _captureManager = new MediaCapture();
            await _captureManager.InitializeAsync();
        }

        private async void StartWebCam()
        {
            try
            {
                if (_captureManager != null)
                {
                    capturePreview.Source = _captureManager;
                    await _captureManager.StartPreviewAsync();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception thrown in {0}. {1}", e.Source, e.Message);
                Debug.WriteLine(e.StackTrace);
            }
        }

        private async void StopWebCam()
        {
            try
            {
                if (_captureManager != null)
                {
                    await _captureManager.StopPreviewAsync();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception thrown in {0}. {1}", e.Source, e.Message);
                Debug.WriteLine(e.StackTrace);
            }
        }
    }
}
